const { HttpException } = require('../core/http-exception')
const { enviroment } = require('../config/config')

const catchError = async (ctx, next) => {
  try {
    await next()
  } catch (error) {
    const isHttpException = error instanceof HttpException
    const isDev = enviroment === 'dev'

    if(isDev && !isHttpException) { // 如果是开发环境，并且不是自定义的HttpException 则直接抛出错误
      throw error
    }
    if(isHttpException) { // 处理自己定义的异常
      ctx.body = {
        msg: error.msg,
        errorCode: error.errorCode,
        request: `${ctx.method} ${ctx.request.path}`
      }
      ctx.status = error.code
      return
    }
    ctx.body = {
      msg: '抱歉，服务器发生了异常',
      errorCode: 999,
      request: `${ctx.method} ${ctx.request.path}`
    }
    ctx.status = 500
  }
}

module.exports = catchError